package com.wp.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.wp.common.CURDUtil;
import com.wp.common.CommonConstant;
import com.wp.common.MD5Util;
import com.wp.common.RequestUtil;
import com.wp.common.ViewNames;

@Controller
public class UserLoginController{
	private static Logger log = Logger.getLogger(UserLoginController.class);
	//验证用户登陆，成功就返回成功页面，失败则返回失败页面
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping("login.do")
	public ModelAndView userLogin(HttpServletRequest req,Model model){
		Map params = RequestUtil.getParams(req);
		Map resultMap = new HashMap();//返回的参数
		
		String pwd = (String)params.get("password");
		params.remove("password");
		params.put("password", MD5Util.makeMode(pwd));
		try{
			int isExists = (Integer)CURDUtil.queryObject("users.userIsExists", params);
			if(isExists>0){
				// 获取用户详细信息
				resultMap = (Map) CURDUtil.queryObject("users.userDetailInfo", params);
				//获取一级标题信息
				List<Map<String,Object>> menuLists = CURDUtil.queryList("users.queryMenuLists",params);
				//根据第一个一级标题获取默认展示的二级标题信息
				if(null != menuLists && menuLists.size()>0){
					List<Map<String,Object>> secondMenuLists = CURDUtil.queryList("users.querySecondMenuLists",menuLists.get(0));
					model.addAttribute("secondMenuLists", secondMenuLists);
				}
				model.addAllAttributes(resultMap);
				model.addAttribute("menuLists", menuLists);
				HttpSession session = req.getSession();
				session.setAttribute(CommonConstant.USER_ID,params.get("username"));
				return new ModelAndView("successView");
			}
		}catch(Exception e){
			return new ModelAndView(ViewNames.failed);
		}
			return new ModelAndView(ViewNames.failed);
	}
	
	public ModelAndView userLoginout(HttpServletRequest req){
		HttpSession session = req.getSession();
		session.invalidate();
		return new ModelAndView(ViewNames.blank);
	}
}
